package views.seeker;

import org.intellij.lang.annotations.Language;
import tools.Hint;
import utils.DBUtil;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
/*ok*/

public class Seeker_Update_Delete extends JFrame {
    private JScrollPane jsp = new JScrollPane();
    ImageIcon imageIcon = new ImageIcon("src/images/seeker.png");
    private String[] table_title = {"编号", "身份证号", "姓名", "性别", "年龄", "联系电话", "聘用情况"};
    private JTable table = new JTable();
    private JButton btn_change = new JButton("修改");
    private JButton btn_delete = new JButton("删除");
    private MyModel model;
    private JLabel jL_id = new JLabel("编号:");
    private JLabel jL_identity = new JLabel("身份证号:");
    private JLabel jl_seekername = new JLabel("姓名：");
    private JLabel jl_gender = new JLabel("性别：");
    private JLabel jl_age = new JLabel("年龄：");
    private JLabel jl_contact_phone = new JLabel("联系电话：");
    private JLabel jl_ishired = new JLabel("是否录用：");
    private JTextField jT_id = new JTextField();
    private JTextField jT_identity = new JTextField();
    private JTextField jT_seekername = new JTextField();
    private JComboBox<String> jC_seekergender = new JComboBox<String>();
    private JTextField jT_seekerage = new JTextField();
    private JTextField jT_contact_phone = new JTextField();
    private JTextField jT_ishird = new JTextField();
    private JButton btn_find = new JButton("查找");
    private JTextField jT_find = new JTextField();
    private Panel panBtn = new Panel();
    private Panel panLab = new Panel();

    public Seeker_Update_Delete() {
        this.setSize(600, 600);
        setTitle("求职者信息修改与删除");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        setIconImage(imageIcon.getImage().getScaledInstance(80, 80, Image.SCALE_DEFAULT));
        model = new MyModel("select * from job_seeker");
        table.setModel(model);
        // 修改列名称

        for (int i = 0; i < table_title.length; i++) {
            table.getColumnModel().getColumn(i).setHeaderValue(table_title[i]);
        }
        DefaultTableCellRenderer r = new DefaultTableCellRenderer();
        r.setHorizontalAlignment(JLabel.CENTER);
        table.setDefaultRenderer(Object.class, r);
        // 设置可见视图的接口
        jsp.setViewportView(table);
        // 定义表格 宽600，高度200
        jsp.setPreferredSize(new Dimension(600, 300));
        // 设置横向和垂直滚动条可见
        jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

        panBtn.add(btn_change);
        panBtn.add(btn_delete);
        // 设置中间的panel布局为空
        panLab.setLayout(null);

        //todo:查找情况

        JRadioButton JR_findByIdentity = new JRadioButton("按身份证查找");
        JRadioButton JR_findByName = new JRadioButton("按姓名查找");
        JRadioButton JR_findByishired = new JRadioButton("按聘用情况查找");
        JR_findByIdentity.setSelected(true); // 默认选择按身份证查找
        // 加入组，避免出现可以两个都选择的情况
        ButtonGroup bg = new ButtonGroup();
        bg.add(JR_findByIdentity);
        bg.add(JR_findByName);
        bg.add(JR_findByishired);

        // 给组件设置位置
        JR_findByIdentity.setSize(100, 30);
        JR_findByIdentity.setLocation(40, 20);

        JR_findByName.setSize(100, 30);
        JR_findByName.setLocation(140, 20);

        JR_findByishired.setSize(100, 30);
        JR_findByishired.setLocation(240, 20);


        String hint_find = "请输入内容";

        // 给组件设置位置
        jT_find.setSize(140, 30);
        jT_find.setLocation(350, 20);
        jT_find.addFocusListener(new Hint(jT_find, hint_find));

        btn_find.setSize(80, 30);
        btn_find.setLocation(500, 20);

        jL_id.setSize(100, 100);
        jL_id.setLocation(10, 30);
        jL_id.setHorizontalAlignment(JLabel.RIGHT);
        jT_id.setSize(150, 25);
        jT_id.setLocation(110, 65);

        jL_identity.setSize(100, 100);
        jL_identity.setLocation(280, 30);
        jL_identity.setHorizontalAlignment(JLabel.RIGHT);
        jT_identity.setSize(150, 25);
        jT_identity.setLocation(380, 70);

        jl_seekername.setSize(100, 100);
        jl_seekername.setLocation(10, 90);
        jl_seekername.setHorizontalAlignment(JLabel.RIGHT);
        jT_seekername.setSize(150, 25);
        jT_seekername.setLocation(110, 130);

        jl_gender.setSize(100, 100);
        jl_gender.setLocation(280, 90);
        jl_gender.setHorizontalAlignment(JLabel.RIGHT);
        jC_seekergender.setSize(150, 25);
        jC_seekergender.setLocation(380, 130);
        jC_seekergender.addItem("男");
        jC_seekergender.addItem("女");
        jC_seekergender.setSelectedIndex(-1);

        jl_age.setSize(100, 100);
        jl_age.setLocation(10, 150);
        jl_age.setHorizontalAlignment(JLabel.RIGHT);
        jT_seekerage.setSize(150, 25);
        jT_seekerage.setLocation(110, 190);


        jl_contact_phone.setSize(100, 100);
        jl_contact_phone.setLocation(280, 150);
        jl_contact_phone.setHorizontalAlignment(JLabel.RIGHT);
        jT_contact_phone.setSize(150, 25);
        jT_contact_phone.setLocation(380, 190);

        jl_ishired.setSize(100, 100);
        jl_ishired.setLocation(10, 210);
        jl_ishired.setHorizontalAlignment(JLabel.RIGHT);

        jT_ishird.setSize(150, 25);
        jT_ishird.setLocation(110, 250);


        // 把标签和文本框加到panLab面板中
        panLab.add(jL_id);
        panLab.add(jT_id);

        panLab.add(jL_identity);
        panLab.add(jT_identity);

        panLab.add(jl_seekername);
        panLab.add(jT_seekername);

        panLab.add(jl_gender);
        panLab.add(jC_seekergender);

        panLab.add(jl_age);
        panLab.add(jT_seekerage);

        panLab.add(jl_contact_phone);
        panLab.add(jT_contact_phone);

        panLab.add(jl_ishired);
        panLab.add(jT_ishird);

        panLab.add(JR_findByIdentity);
        panLab.add(JR_findByName);
        panLab.add(JR_findByishired);

        panLab.add(jT_find);
        panLab.add(btn_find);


        this.add(jsp, BorderLayout.NORTH);
        this.add(panLab, BorderLayout.CENTER);
        this.add(panBtn, BorderLayout.SOUTH);

        jT_id.setEditable(false);
        // 获取表里的值
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int selRow = table.getSelectedRow();
                String Id = table.getValueAt(selRow, 0).toString().trim();
                String identity = table.getValueAt(selRow, 1).toString().trim();
                String seekername = table.getValueAt(selRow, 2).toString().trim();
                String gender = table.getValueAt(selRow, 3).toString().trim();
                String age = table.getValueAt(selRow, 4).toString().trim();
                String contactphone = table.getValueAt(selRow, 5).toString().trim();
                String ishired = table.getValueAt(selRow, 6).toString().trim();

                jT_id.setText(Id);
                jT_identity.setText(identity);
                jT_seekername.setText(seekername);
                jC_seekergender.setSelectedItem(gender);
                jT_seekerage.setText(age);
                jT_contact_phone.setText(contactphone);
                jT_ishird.setText(ishired);
            }
        });

        btn_find.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                if (JR_findByIdentity.isSelected()) {
                    String s = jT_find.getText().trim();
                    if (s.equals(hint_find)) {
                        JOptionPane.showMessageDialog(null, "请输入内容", "警告", JOptionPane.WARNING_MESSAGE);
                    } else {
                        @Language("MySQL")
                        String sql = "select * from job_seeker where identityNum like '%" +
                                s
                                + "%';";
                        model = new MyModel(sql);
                        table.setModel(model);
                        for (int i = 0; i < table_title.length; i++) {
                            table.getColumnModel().getColumn(i).setHeaderValue(table_title[i]);
                        }
                        DefaultTableCellRenderer r = new DefaultTableCellRenderer();
                        r.setHorizontalAlignment(JLabel.CENTER);
                        table.setDefaultRenderer(Object.class, r);
                    }
                } else if (JR_findByishired.isSelected()) {
                    String s = jT_find.getText().trim();
                    if (s.equals(hint_find)) {
                        JOptionPane.showMessageDialog(null, "请输入内容", "警告", JOptionPane.WARNING_MESSAGE);
                    } else {
                        @Language("MySQL")
                        String sql = "select * from job_seeker where ishired like '%" +
                                s
                                + "%';";
                        model = new MyModel(sql);
                        table.setModel(model);
                        for (int i = 0; i < table_title.length; i++) {
                            table.getColumnModel().getColumn(i).setHeaderValue(table_title[i]);
                        }
                        DefaultTableCellRenderer r = new DefaultTableCellRenderer();
                        r.setHorizontalAlignment(JLabel.CENTER);
                        table.setDefaultRenderer(Object.class, r);
                    }
                } else {
                    String s = jT_find.getText().trim();
                    if (s.equals(hint_find)) {
                        JOptionPane.showMessageDialog(null, "请输入内容", "警告", JOptionPane.WARNING_MESSAGE);
                    } else {
                        @Language("MySQL")
                        String sql = "select * from job_seeker where name like '%" +
                                s + "%';";
                        model = new MyModel(sql);
                        table.setModel(model);
                        for (int i = 0; i < table_title.length; i++) {
                            table.getColumnModel().getColumn(i).setHeaderValue(table_title[i]);
                        }
                        DefaultTableCellRenderer r = new DefaultTableCellRenderer();
                        r.setHorizontalAlignment(JLabel.CENTER);
                        table.setDefaultRenderer(Object.class, r);
                    }
                }
            }
        });

        btn_change.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                int id = Integer.parseInt(jT_id.getText());
                String identiy = jT_identity.getText().trim();
                String name = jT_seekername.getText().trim();
                String gender = jC_seekergender.getSelectedItem().toString().trim();
                String age = jT_seekerage.getText().trim();
                String phone = jT_contact_phone.getText().trim();
                String ishired = jT_ishird.getText().trim();
                Statement stmt = DBUtil.getStatement();
                String sql = "update job_seeker set identityNum = '"
                        + identiy
                        + "',name='"
                        + name
                        + "',gender='"
                        + gender
                        + "',age="
                        + age
                        + ",contact_phone= '"
                        + phone
                        + "',ishired='" +
                        ishired
                        + "' where seeker_id="
                        + id
                        + ";";
                try {
                    stmt.executeUpdate(sql);
                    JOptionPane.showMessageDialog(null, "修改成功。");
                    jT_id.setText("");
                    jT_identity.setText("");
                    jT_seekername.setText("");
                    jT_contact_phone.setText("");
                    jT_ishird.setText("");
                    // 实时更新表
                    @Language("MySQL")
                    String updateSQL = "SELECT * from job_seeker;";
                    model = new MyModel(updateSQL);
                    table.setModel(model);
                    for (int i = 0; i < table_title.length; i++) {
                        table.getColumnModel().getColumn(i).setHeaderValue(table_title[i]);
                    }
                    DefaultTableCellRenderer r = new DefaultTableCellRenderer();
                    r.setHorizontalAlignment(JLabel.CENTER);
                    table.setDefaultRenderer(Object.class, r);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });

        btn_delete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                int i = Integer.parseInt(jT_id.getText().trim());
                int result = JOptionPane.showConfirmDialog(null, "确定删除吗?", "提示", JOptionPane.YES_NO_OPTION);
                if (result == JOptionPane.YES_OPTION) {
                    Statement stmt = DBUtil.getStatement();
                    @Language("MySQL")
                    String sql3 = "select job_id from job_match where seeker_id=" + i;
                    String sql = "delete from job_seeker where seeker_id = " + i + ";";

                    try {
                        ResultSet rs = stmt.executeQuery(sql3);
                        if (!rs.next()) {
                            stmt.executeUpdate(sql);
                            JOptionPane.showMessageDialog(null, "已删除！");
                            // 实时更新表格数据
                            @Language("MySQL")
                            String sql2 = "SELECT * from job_seeker;";
                            model = new MyModel(sql2);
                            table.setModel(model);
                            for (int k = 0; k < table_title.length; k++) {
                                table.getColumnModel().getColumn(k).setHeaderValue(table_title[k]);
                            }
                            DefaultTableCellRenderer r = new DefaultTableCellRenderer();
                            r.setHorizontalAlignment(JLabel.CENTER);
                            table.setDefaultRenderer(Object.class, r);
                        } else {
                            JOptionPane.showMessageDialog(null, "无法删除", "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                } else {
                    dispose();
                }
            }
        });
    }

    class MyModel extends AbstractTableModel {
        private int row;
        private int column;
        private ResultSet rs;
        private Statement stmt;

        public MyModel(@Language("MySQL") String sql) {
            stmt = DBUtil.getStatement();
            try {
                rs = stmt.executeQuery(sql);
                rs.last();// 将光标移到最后一行
                row = rs.getRow();// 获取行号(最大行索引)
                ResultSetMetaData rsmd = rs.getMetaData();// 通过结果集对象来获取
                column = rsmd.getColumnCount();// 获取列数
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public int getColumnCount() {
            return column;
        }

        @Override
        public int getRowCount() {
            return row;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object value = null;
            try {
                rs.absolute(rowIndex + 1);
                value = rs.getString(columnIndex + 1);// 获取表里的数据
            } catch (Exception e) {
                e.printStackTrace();
            }
            return value;
        }
    }
}
